﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SharpDiary.Core.Common;
using SharpDiary.Core.Attributes;
using SharpDiary.Core.Data;
using SharpDiary.Core.Utility;
using SharpDiary.Reminder;
using SharpDiary.Core.ORMapping;

namespace SharpDiary.Task
{
    [GuiModule("fd8e906c-9275-4375-9217-aeb0410a7ba2", "Reminder", "Ray Shaw(demogodyou@gmail.com)")]
    public partial class frmReminder : GuiModuleUIBase
    {
        #region Fields & Properties

        private DataTable _source;

        private string _wavFileName = string.Empty;

        #endregion

        #region Constructors

        public frmReminder()
        {
            InitializeComponent();

            _wavFileName = System.IO.Path.Combine(Application.StartupPath, "reminder.wav");
            CheckReminders();
            timerReminder.Start();
        }

        #endregion

        #region Methods

        public override string GetSettingsKeyName()
        {
            return this.Name;
        }

        /// <summary>
        /// 检查是否有到期的提醒。
        /// </summary>
        private void CheckReminders()
        {
            StringBuilder sql = new StringBuilder();
            sql.AppendLine("SELECT * FROM ReminderInfo");
            sql.AppendLine("where status = 1 and (");
            sql.AppendLine("  (ReminderType = 0 and AlarmDatetime <= @now)");
            sql.AppendLine("  or (ReminderType = 1 and ");
            sql.AppendLine("      strftime('%H', alarmDatetime) = strftime('%H', @now)");
            sql.AppendLine("      and strftime('%M', alarmDatetime) = strftime('%M', @now))");
            sql.AppendLine(")");

            DataAccessService das = Utils.GetDataAccessServiceInstance();
            reminderInfoListControl.ShowItems(sql.ToString(),
                das.CreateParameter("@now", DbType.DateTime, DateTime.Now));

            this.Text = reminderInfoListControl.Items.Count + " 个提醒";

            if (reminderInfoListControl.Items.Count > 0)
            {
                this.Show();

                if (this.WindowState == FormWindowState.Minimized)
                {
                    this.WindowState = FormWindowState.Normal;
                }

                this.Activate();
                this.BringToFront();

                Utils.PlaySound(_wavFileName);
            }
        }


        #endregion

        private void timerReminder_Tick(object sender, EventArgs e)
        {
            //是否禁用了提醒？
            if (UserSettings.GetInstance().GetSettingValue("ReminderState", "0") == "0")
            {
                return;
            }

            CheckReminders();
        }

        private void frmReminder_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.Hide();
            e.Cancel = true;
        }

        public override void Display()
        {
            //base.Display();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 延迟提醒指定时间。
        /// </summary>
        /// <param name="timeSpan"></param>
        /// <returns></returns>
        private bool DelayReminders(TimeSpan value)
        {
            foreach (ReminderInfoListItemControl item in reminderInfoListControl.Items)
            {
                if (item.Reminder != null)
                {
                    ReminderInfo reminder = item.Reminder;
                    reminder.AlarmDatetime = reminder.AlarmDatetime.Add(value);

                    if (!ReminderInfo.Update<ReminderInfo>(reminder))
                    {
                        return false;
                    }
                }
            }

            return true;
        }

        /// <summary>
        /// 取消所有提醒。
        /// </summary>
        /// <returns></returns>
        private bool CancelAllReminders()
        {
            foreach (ReminderInfoListItemControl item in reminderInfoListControl.Items)
            {
                if (item.Reminder != null)
                {
                    ReminderInfo reminder = item.Reminder;
                    reminder.Status = 0;

                    if (!ReminderInfo.Update<ReminderInfo>(reminder))
                    {
                        return false;
                    }
                }
            }

            return true;
        }

        private void btn5MinsLater_Click(object sender, EventArgs e)
        {
            if (DelayReminders(new TimeSpan(0, 5, 0)))
            {
                ShowMessage("5 分钟后再会再次提醒您。");
                DelayClose();
            }
            else
            {
                ShowMessage("操作失败。");
            }
        }

        private void btnClearAll_Click(object sender, EventArgs e)
        {
            if (CancelAllReminders())
            {
                ShowMessage("以下所有将不再提醒您。");
                DelayClose();
            }
            else
            {
                ShowMessage("操作失败。");
            }
        }

        private void reminderInfoListControl_ControlRemoved(object sender, ControlEventArgs e)
        {
            btnClearAll.Enabled = reminderInfoListControl.Items.Count > 0;
            btn5MinsLater.Enabled = btn5MinsLater.Enabled;
        }
    }
}
